package com.itheima.service.backend.impl;

import com.itheima.common.entity.Result;
import com.itheima.common.utils.DateUtils;
import com.itheima.mapper.backend.ReportMapper;
import com.itheima.service.backend.ReportService;
import com.itheima.vo.*;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.YearMonth;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 统计报表服务实现
 */
@Service
public class ReportServiceImpl implements ReportService {

    @Autowired
    private ReportMapper reportMapper;
    @Autowired
    private ReportService reportService;

    /**
     * 获取会员数量
     *
     * @return
     */
    @Override
    public Object getMemberReport() throws Exception {
        List<String> months = new ArrayList<>();
        List<Integer> memberCount = new ArrayList<>();
        //  创建会员报表对象
        MemberReportVO memberReportVO = new MemberReportVO();
        // 获取当前日期
        Date nowDay = DateUtils.getToday();
        // 查询会员的最早注册日期
        Date firstDay = reportMapper.minRegTime();
        // 根据最早注册日期和当前日期获取月份列表
        months = DateUtils.getMonthBetween(DateUtils.parseDate2String(firstDay), DateUtils.parseDate2String(nowDay), "yyyy-MM");
        // 月份列表改为月份最后一天列表
        for (int i = 0; i < months.size(); i++) {
            //根据月份获取这个月的最后一天
            YearMonth yearMonth = YearMonth.parse(months.get(i));
            LocalDate lastDay = yearMonth.atEndOfMonth();
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
            String month = lastDay.format(formatter);
            months.set(i, month);
            memberCount.add(reportMapper.findmemberCounts(DateUtils.parseString2Date(month)));
        }
        memberReportVO.setMonths(months);
        memberReportVO.setMemberCount(memberCount);
        System.out.println(memberReportVO);
        return memberReportVO;
    }

    /**
     * 获取套餐预约数量
     *
     * @return
     */
    @Override
    public Object getSetmealReport() {
        SetmealReportVO setmealReport = new SetmealReportVO();
        // 查询套餐预约名称和数量
        List<SetmealCountVO> list = reportMapper.findSetmealNumber();
        List<String> list1 = new ArrayList<>();
        for (int i = 0; i < list.size(); i++) {
            list1.add(list.get(i).getName());
        }
        setmealReport.setSetmealNames(list1);
        setmealReport.setSetmealCount(list);
        return setmealReport;
    }

    /**
     * 获取运营数据
     *
     * @return
     */
    @Override
    public BusinessRopertDateVO getBusinessReport() throws Exception {
        BusinessRopertDateVO businessRopertDate = new BusinessRopertDateVO();
        //获取今天的日期
        Date today = DateUtils.getToday();
        //获取当前时间所在周的开始日期
        Date thisWeekMonday = DateUtils.getThisWeekMonday();
        //获取当前时间所在周的结束日期
        Date thisWeekSunday = DateUtils.getSundayOfThisWeek();
        //获取本月的开始日期
        Date thisMonthFirstDay = DateUtils.getFirstDay4ThisMonth();
        //获取本月的结束日期
        Date thisMonthLastDay = DateUtils.getLastDay4ThisMonth();
        //封装数据
        businessRopertDate.setReportDate(DateUtils.parseDate2String(today));
        businessRopertDate.setTodayNewMember(reportMapper.todayNewMember(today));
        businessRopertDate.setTotalMember(reportMapper.totalMember());
        businessRopertDate.setThisWeekNewMember(reportMapper.thisWeekNewMember(thisWeekMonday, thisWeekSunday));
        businessRopertDate.setThisMonthNewMember(reportMapper.thisMonthNewMember(thisMonthFirstDay));
        businessRopertDate.setTodayOrderNumber(reportMapper.todayOrderNumber(today));
        businessRopertDate.setTodayVisitsNumber(reportMapper.todayVisitsNumber(today));
        businessRopertDate.setThisWeekOrderNumber(reportMapper.thisWeekOrderNumber(thisWeekMonday, thisWeekSunday));
        businessRopertDate.setThisWeekVisitsNumber(reportMapper.thisWeekVisitsNumber(thisWeekMonday, thisWeekSunday));
        businessRopertDate.setThisMonthOrderNumber(reportMapper.thisMonthOrderNumber(thisMonthFirstDay, thisMonthLastDay));
        businessRopertDate.setThisMonthVisitsNumber(reportMapper.thisMonthVisitsNumber(thisMonthFirstDay, thisMonthLastDay));
        List<HotSetmeal2VO> list = reportMapper.hotSetmeal();
        List<HotSetmealVO> list1 = new ArrayList<>();
        Integer sum = reportMapper.orderSum();
        for (int i = 0; i < list.size(); i++) {
            list1.add(new HotSetmealVO
                    (list.get(i).getName(), list.get(i).getSetmealCount(), list.get(i).getSetmealCount() / sum));
        }
        businessRopertDate.setHotSetmeal(list1);

        return businessRopertDate;
    }

    /**
     * 导出运营数据报表
     *
     * @param request
     * @param response
     * @throws Exception
     */
    @Override
    public void exportBusinessReport(HttpServletRequest request, HttpServletResponse response) throws Exception {
        //设置响应内容类型为excel
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        //获取报表数据
        BusinessRopertDateVO businessRopertDateVO = reportService.getBusinessReport();
        //获取数据
        List<HotSetmealVO> hotSetmealVOS = businessRopertDateVO.getHotSetmeal();
        //创建一个Excel表格对象
        InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("templates/report_template.xlsx");
        try {
            //基于提供好的模板文件创建一个新的Excel表格对象
            XSSFWorkbook excel = new XSSFWorkbook(inputStream);
            //获得Excel文件中的一个Sheet页
            XSSFSheet sheet = excel.getSheet("Sheet1");
            //第3行第6列的值设置为当前日期
            sheet.getRow(2).getCell(5).setCellValue(businessRopertDateVO.getReportDate());
            XSSFRow row = sheet.getRow(4);//获得第5行
            row.getCell(5).setCellValue(businessRopertDateVO.getTodayNewMember());//获取单元格，设置参数
            row.getCell(7).setCellValue(businessRopertDateVO.getTotalMember());//获取单元格，设置参数
            row = sheet.getRow(5);
            row.getCell(5).setCellValue(businessRopertDateVO.getThisWeekNewMember());
            row.getCell(7).setCellValue(businessRopertDateVO.getThisMonthNewMember());
            row = sheet.getRow(7);
            row.getCell(5).setCellValue(businessRopertDateVO.getTodayOrderNumber());
            row.getCell(7).setCellValue(businessRopertDateVO.getTodayVisitsNumber());
            row = sheet.getRow(8);
            row.getCell(5).setCellValue(businessRopertDateVO.getThisWeekOrderNumber());
            row.getCell(7).setCellValue(businessRopertDateVO.getThisWeekVisitsNumber());
            row = sheet.getRow(9);
            row.getCell(5).setCellValue(businessRopertDateVO.getThisMonthOrderNumber());
            row.getCell(7).setCellValue(businessRopertDateVO.getThisMonthVisitsNumber());
            for (int i = 0; i < hotSetmealVOS.size(); i++) {
                row = sheet.getRow(12 + i);
                row.getCell(4).setCellValue(hotSetmealVOS.get(i).getName());
                row.getCell(5).setCellValue(hotSetmealVOS.get(i).getSetmeal_count());
                row.getCell(6).setCellValue(hotSetmealVOS.get(i).getProportion());
            }
            //通过输出流将文件下载到客户端浏览器中
            ServletOutputStream out = response.getOutputStream();
            excel.write(out);
            //关闭资源
            out.flush();
            out.close();
            excel.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
